package com.hc.java.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLIB代理接口
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/8 22:05
 */
public class CglibProxyInterfaceDemo {
    public static void main(String[] args) {
        TestCglib testCglib = new TestCglib();
        TestInterface instance = (TestInterface) testCglib.getInstance(TestInterface.class);
        System.out.println(instance.getHelloWorld());
    }
}

interface TestInterface {
    String getHelloWorld();
}
class TestCglib implements MethodInterceptor {

    public Object getInstance(Class clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        // 回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        return method.getName();
    }
}